namespace Legend.IoCo
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public static class Container
    {
        public static void RegisterAs<T>(this IContainer container, Func<IComponentResolver, T> creator)
        {
            container.Register(new [] { typeof(T) }, c => creator(c));
        }

        public static T Resolve<T>(this IComponentResolver componentResolver)
        {
            return (T)componentResolver.Resolve(typeof(T));
        }

        public static object Resolve(this IComponentResolver componentResolver, Type componentType)
        {
            object result = null;

            if (!componentResolver.TryResolve(componentType, out result))
            {
                throw new ComponentResolveException("Unable to resolve component " + componentType.FullName);
            }

            return result;
        }

        public static void RegisterAs<T>(this IContainer container, IEnumerable<Type> additionallySupportedTypes, Func<IComponentResolver, T> creator)
        {
            container.Register(new[] { typeof(T) }.Concat(additionallySupportedTypes), c => creator(c));
        }
    }
}